<template>
	<view class="share-container">
		<view class="hm-page__bd  hm-page__spacing">
			<button :style="props.customShareStyle" class="share-btn" plain :size="34" @click="showChannels">分享</button>
		</view>
		<hm-poster :width="750" :height="1250" ref="posterRef" @ready="ready"></hm-poster>
		<u-popup :safe-area-inset-bottom="true" :mask-close-able="true" :border-radius="10" mode="bottom"
			v-model="channelsShow">
			<view class="channel-btns">
				<button open-type="share" class="friend btn ss-reset-button">
					<u-icon label-pos="bottom" label="微信好友" color="#51a838" name="weixin-circle-fill"
						size="56"></u-icon>
				</button>
				<button class="btn ss-reset-button" @click="sharePoster">
					<u-icon label-pos="bottom" label="保存海报" name="photo-fill" color="#f3bd41" size="56"></u-icon>
				</button>
			</view>
		</u-popup>
		<u-popup v-model="showPoster" close-icon-color="#ffffff" mode="center" @close="close" :closeable="false"
			:mask-close-able="false">
			<view class="preview">
				<image class="preview-image" :src="sharePosterUrl" mode="widthFix"></image>
				<view class="btns">
					<button class="cancel-btn btn" @click="close">取消</button>
					<button class="poster-btn btn" @click="savePoster">保存海报</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script lang="ts" setup>
	import { ref, defineProps } from 'vue';
	import hmPoster from '@/common/components/hm-poster/hm-poster.vue';


	const vk = uni.vk;

	const props = defineProps({
		templateData: {
			type: Object,
			default: {}
		},
		customShareStyle: {
			type: String,
			default: ''
		}
	})

	const showPoster = ref(false);
	const close = () => {
		showPoster.value = false;
	}
	let sharePosterData = [];

	const channelsShow = ref(false);
	const showChannels = () => {
		channelsShow.value = true;
	}

	const getSuncode = (userInfo) : Promise<string> => {
		const pages = getCurrentPages();
		const page = `${pages[pages.length - 1].route}`;
		const scene = `t=${props.templateData.template_id}&i=${userInfo.my_invite_code}`;
		let env_version = 'release';
		if (__wxConfig && __wxConfig.envVersion) {
			env_version = __wxConfig.envVersion
		}
		console.log('env_version :', env_version);
		return new Promise((resolve, reject) => {
			vk.callFunction({
				url: 'client/template/kh/getSuncode',
				title: '请求中...',
				data: {
					page,
					env_version, // 要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
					scene,
				},
				success: (data) => {
					resolve(data.base64)
				},
				fail: (e) => {
					reject(e)
				}
			});
		})
	}

	let suncode = '';
	const initShare = async () => {
		console.log('props.templateData', props.templateData);
		const userInfo = vk.vuex.get('$user.userInfo');
		if (!suncode) {
			try {
				suncode = await getSuncode(userInfo);
			} catch (err) {
				console.log(err);
				return vk.toast('分享初始化失败，请稍后再试！');
			}
		}

		if (!suncode || !userInfo) {
			return vk.toast('分享初始化失败，请稍后再试！');
		};

		sharePosterData = [
			{
				type: 'rect',
				style: {
					left: 0,
					top: 0,
					width: 750,
					height: 1250,
					backgroundColor: '#ffffff',
					borderRadius: 0
				}
			},
			{
				type: 'image',
				src: props.templateData.previewUrl[0],
				imgType: 2,
				style: {
					left: 50,
					top: 50,
					width: 650,
					height: 650,
					borderRadius: 20
				}
			},
			{
				type: 'rect',
				style: {
					left: 50,
					top: 690,
					width: 650,
					height: 230,
					backgroundColor: '#fdf3ec',
					borderRadius: 0
				}
			},
			{
				type: 'rect',
				style: {
					left: 50,
					top: 700,
					width: 650,
					height: 230,
					backgroundColor: '#fdf3ec',
					borderRadius: 22
				}
			},
			{
				type: 'text',
				text: '“',
				style: {
					left: 90,
					top: 780,
					fontSize: 68,
					color: '#000000',
					width: 360,
					rows: 2,
					lineHeight: 68
				}
			},
			{
				type: 'text',
				text: props.templateData.shareText || '送你一个意义非凡的头像快来领取吧!',
				style: {
					left: 385,
					top: 800,
					fontSize: 38,
					color: '#000000',
					width: 380,
					rows: 2,
					lineHeight: 48,
					textAlign: 'center'
				}
			},
			{
				type: 'text',
				text: '”',
				style: {
					left: 620,
					top: 900,
					fontSize: 66,
					color: '#000000',
					width: 360,
					rows: 1,
					lineHeight: 68
				}
			},
			{
				type: 'text',
				text: '来趣拿图，制作你的专属头像',
				style: {
					left: 40,
					top: 1040,
					fontSize: 32,
					color: '#000000',
					width: 450,
					rows: 1,
					lineHeight: 36
				}
			},
			{
				type: 'text',
				text: '情侣头像 | 亲子头像 | 姓氏谐音梗 |可爱A卡通头像 ...',
				style: {
					left: 40,
					top: 1086,
					fontSize: 26,
					color: '#95918f',
					width: 392,
					rows: 2,
					lineHeight: 36
				}
			},
			{
				type: 'image',
				src: suncode,
				imgType: 3,
				style: {
					left: 520,
					top: 980,
					width: 200,
					height: 200,
					borderRadius: 100
				}
			},
			{
				type: 'text',
				text: '长按识别二维码',
				style: {
					left: 536,
					top: 1220,
					fontSize: 22,
					color: '#95918f',
					width: 360,
					rows: 1,
					lineHeight: 22
				}
			},
		]
	}

	let init = false;
	const sharePosterUrl = ref('');

	const ready = () => {
		init = true
	}

	let poster = ref(null);
	const posterRef = el => poster = el;
	let loading = false;
	const sharePoster = async () => {
		await initShare();
		if (!init || !poster) return;

		if (sharePosterUrl.value) {
			showPoster.value = true;
			return
		}
		uni.showLoading({
			title: '绘制海报中...'
		})
		loading = true;
		console.log('sharePosterData', sharePosterData);
		try {
			poster.draw(sharePosterData, (filePath) => {
				//绘制图片路径
				sharePosterUrl.value = filePath;
				showPoster.value = true;
				if (loading) {
					uni.hideLoading();
				}
				loading = false;
			})
		} catch (err) {
			console.log(err);
			vk.toast('海报生成失败，请重试');
		}
	}

	const savePoster = () => {
		sharePosterUrl.value
		uni.saveImageToPhotosAlbum({
			filePath: sharePosterUrl.value,
			success: () => {
				vk.toast('保存成功');
			},
			fail: () => {
				vk.toast('保存失败');
			}
		})
	}
</script>

<style scoped lang="scss">
	.preview {
		.preview-image {
			width: 600rpx;
		}
	}

	.btns {
		display: flex;
		justify-content: space-between;
		margin-top: 30rpx;

		.btn {
			display: inline-block;
			width: 200rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 20px;
			background-color: #ed5a3a;
			color: #ffffff;
			text-align: center;
			margin: 0 20rpx;
			font-size: 28rpx;
		}

		.cancel-btn {
			background-color: #ffffff;
			color: #a9a9a9;
		}
	}

	.share-btn {
		flex: 1;
		height: 90rpx;
		font-weight: bold;
		font-size: 32rpx;
		letter-spacing: 8;
		font-style: normal;
		font-weight: 500;
		color: #627AF8;
		border-radius: 38px;
		border-color: #627AF8;
	}

	.channel-btns {
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding: 60rpx;
		background-color: #ffffff;

		.btn {
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			width: 50%;

			.icon {
				background-color: #f5f7fe;
				border-radius: 25px;
				height: 100rpx;
				width: 100rpx;
			}
		}

		.friend {
			position: relative;

			&::after {
				position: absolute;
				left: 0;
				top: 0;
				content: '';
				height: 200%;
				width: 200%;
				border-radius: 0;
				border-right: 1px solid #dddddd;
				transform: scale(0.5);
				transform-origin: 0 0;
			}
		}
	}
</style>